
# 定时任务相关视图
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.shortcuts import render, redirect, get_object_or_404
from LogisticsCard.tasks.task_dict import TASK_DICT, TASK_LIST
from LogisticsCard.models import PeriodicTaskConfig, Log


@login_required
def tasks_view(request):
    """
    定时任务列表视图，分页展示所有定时任务配置。
    :param request: HttpRequest对象
    :return: 渲染定时任务列表页面
    """
    tasks = PeriodicTaskConfig.objects.filter(delete_at__isnull=True).order_by('-id')
    paginator = Paginator(tasks, 20)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return render(request, 'tasks/index.html', {'page_obj': page_obj, 'task_labels': TASK_DICT})


@login_required
def add_task_view(request):
    """
    定时任务创建视图，处理定时任务表单提交。
    :param request: HttpRequest对象
    :return: 渲染定时任务创建页面或跳转到列表
    """
    allowed_tasks = TASK_LIST
    if request.method == 'POST':
        data = {k: request.POST.get(k) for k in ['name','task','crontab','remark']}
        valid_values = [t['value'] for t in allowed_tasks]
        if data['task'] not in valid_values:
            return render(request, 'tasks/add.html', {'error': '请选择有效的任务', 'allowed_tasks': allowed_tasks})
    task_obj = PeriodicTaskConfig.objects.create(**data, delete_at=None)
    Log.objects.create(user=request.user, action='other', detail=f'添加任务:{task_obj.name}')
    return redirect('/tasks/')
    return render(request, 'tasks/add.html', {'allowed_tasks': allowed_tasks})


@login_required
def edit_task_view(request, task_id):
    """
    定时任务编辑视图，处理定时任务信息更新。
    :param request: HttpRequest对象
    :param task_id: 定时任务ID
    :return: 渲染定时任务编辑页面或跳转到列表
    """
    task = PeriodicTaskConfig.objects.get(id=task_id, delete_at__isnull=True)
    allowed_tasks = TASK_LIST
    if request.method == 'POST':
        task.name = request.POST.get('name')
        task.task = request.POST.get('task')
        task.crontab = request.POST.get('crontab')
        task.remark = request.POST.get('remark')
        task.enabled = request.POST.get('enabled') == 'True'
        task.save()
        Log.objects.create(user=request.user, action='other', detail=f'编辑任务:{task.name}')
        return redirect('/tasks/')
    return render(request, 'tasks/edit.html', {'task': task, 'allowed_tasks': allowed_tasks})

@login_required
def delete_task_view(request, task_id):
    from django.utils import timezone
    PeriodicTaskConfig.objects.filter(id=task_id, delete_at__isnull=True).update(delete_at=timezone.now())
    Log.objects.create(user=request.user, action='other', detail=f'虚拟删除任务 ID:{task_id}')
    return redirect('/tasks/')
